"""
角色管理
"""
import logging

from django.urls import reverse
from django.shortcuts import redirect

from oracle.forms import role
from oracle.views import tools
from oracle.models import ORole
from oracle.base.baseview import judge_render_flag, get_context_data, render_handler

logger = logging.getLogger(__name__)


def role_list(request):
    """
    角色列表
    :param request:
    :return:
    """
    data = {"operation": "list"}
    status = "success"
    template = "oracle/role_list.html"
    role_queryset = ORole.objects.all()
    data["role_list"] = list()
    for obj in role_queryset:
        data["role_list"].append({"title": obj.title, "key": obj.key})

    get_context_data(request, logger, data)
    return render_handler(request, status, template=template, data=data)


def role_add(request):
    """
    创建角色
    :param request:
    :return:
    """
    data = {"operation": "add"}
    status = "success"
    template = None
    method = None

    if request.method == "GET":
        return_url = reverse("oracle:role_list")
        form = role.RoleCreateForm()
        data.update({
            "form": form,
            "form_name": "添加角色",
            "form_description": "",
            "return_url": return_url,
        })
        # 是否强制外部渲染标志
        force_external_render = judge_render_flag(request, render=None)

        if force_external_render == 0:
            template = "oracle/change.html"
        else:
            # 将form类型处理成为json能格式化的数据
            tools.form_object_to_json(data)
    elif request.method == "POST":
        # 验证form
        form = role.RoleCreateForm(request.POST)
        # form合法
        if form.is_valid():
            # 获取form返回的实例，key需要单独生成，所以目前先不进行保存
            obj = form.save(commit=False)
            key = request.POST.get("key")
            key = tools.get_only_key(ORole, key)
            # 定义唯一key并进行保存
            obj.key = key
            obj.save()

            def method(r, t, d):
                return redirect(reverse("oracle:role_list"))
        # 校验没有通过
        else:
            return_url = reverse("oracle:role_list")
            # 设置错误信息，如果外部渲染传给前端
            data.update({
                "form": form,
                "form_name": "添加角色",
                "form_description": "",
                "return_url": return_url,
            })

            # 将form类型处理成为json能格式化的数据
            tools.form_object_to_json(data)

            for item in data["form"]:
                key = data["form"][item]["name"]
                if key in request.POST:
                    data["form"][item]["instance"] = request.POST.get(key)
            status = "model_valid_check_failed"
            template = "oracle/change.html"
    # 非get或者post方法访问进行友好报错处理
    else:
        status = "method_not_allow"
    get_context_data(request, logger, data)
    return render_handler(request, status, method, template, data)


def role_edit(request, key):
    """
    修改角色
    :param request:
    :param key: 要修改的角色索引
    :return:
    """
    data = {"operation": "change"}
    status = "success"
    template = None
    method = None

    # 获取要修改的实例信息
    obj = ORole.objects.filter(key=key).first()
    if request.method == "GET":
        # 如果有实例则返回修改页面信息
        if obj:
            return_url = reverse("oracle:role_list")
            form = role.RoleUpdateForm(instance=obj)
            data.update({
                "form": form,
                "form_name": "修改角色",
                "form_description": "",
                "return_url": return_url,
            })
            # 是否强制外部渲染标志
            force_external_render = judge_render_flag(request, render=None)

            if force_external_render == 0:
                template = "oracle/change.html"
            else:
                # 将form类型处理成为json能格式化的数据
                tools.form_object_to_json(data)
        # 没有实例则返回人性化错误信息
        else:
            # 设置错误信息，如果外部渲染传给前端
            status = "model_object_not_exist"
    elif request.method == "POST":
        if obj:
            post_data = dict()
            for key in role.RoleUpdateForm.base_fields:
                if key in request.POST:
                    post_data[key] = request.POST.get(key)
                else:
                    post_data[key] = getattr(obj, key)

            # 验证form
            form = role.RoleUpdateForm(instance=obj, data=post_data)
            # form合法
            if form.is_valid():
                # 获取form返回的实例，key需要单独生成，所以目前先不进行保存
                form.save()

                def method(r, t, d):
                    return redirect(reverse("oracle:role_list"))
            # 校验没有通过
            else:
                return_url = reverse("oracle:role_list")
                # 设置错误信息，如果外部渲染传给前端
                data.update({
                    "form": form,
                    "form_name": "修改角色",
                    "form_description": "",
                    "return_url": return_url,
                })
                # 是否强制外部渲染标志
                force_external_render = judge_render_flag(request, render=None)

                if force_external_render == 0:
                    template = "oracle/change.html"
                else:
                    # 将form类型处理成为json能格式化的数据
                    tools.form_object_to_json(data)
                status = "model_valid_check_failed"
        # 没有实例则返回人性化错误信息
        else:
            # 设置错误信息，如果外部渲染传给前端
            status = "model_object_not_exist"
    # 非get或者post方法访问进行友好报错处理
    else:
        status = "method_not_allow"
    get_context_data(request, logger, data)
    return render_handler(request, status, method, template, data)


def role_del(request, key):
    """
    删除角色
    :param request:
    :param key: 要删除的角色索引
    :return:
    """
    data = {"operation": "delete"}
    status = "success"
    template = None
    method = None

    # 获取要删除的实例信息
    obj = ORole.objects.filter(key=key).first()
    if request.method == "GET":
        # 如果有实例则返回修改页面信息
        if obj:
            return_url = reverse("oracle:role_list")
            data.update({
                "object": obj.title,
                "form_name": "删除角色",
                "form_description": "",
                "return_url": return_url,
            })

            template = "oracle/delete_confirm.html"
        # 没有实例则返回人性化错误信息
        else:
            # 设置错误信息，如果外部渲染传给前端
            status = "model_object_not_exist"
    elif request.method == "POST":
        if obj:
            # 实例直接进行删除
            obj.delete()

            def method(r, t, d):
                return redirect(reverse("oracle:role_list"))
        # 没有实例则返回人性化错误信息
        else:
            # 设置错误信息，如果外部渲染传给前端
            status = "model_object_not_exist"
    # 非get或者post方法访问进行友好报错处理
    else:
        status = "method_not_allow"
    get_context_data(request, logger, data)
    return render_handler(request, status, method, template, data)
